import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'app_theme.dart';

/// 主题提供者，管理应用主题
class ThemeProvider with ChangeNotifier {
  /// 主题偏好设置的键
  static const String _themePreferenceKey = 'theme_preference';

  /// 当前主题类型
  ThemeType _themeType = ThemeType.light;

  /// 获取当前主题类型
  ThemeType get themeType => _themeType;

  /// 获取当前主题数据
  ThemeData get themeData => AppTheme.theme;

  /// 是否是深色模式
  bool get isDarkMode => _themeType == ThemeType.dark;

  /// 构造函数，初始化主题状态
  ThemeProvider() {
    _loadThemePreference();
  }

  /// 加载主题偏好设置
  Future<void> _loadThemePreference() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final themeIndex = prefs.getInt(_themePreferenceKey) ?? 0;
      _themeType = ThemeType.values[themeIndex];
      AppTheme.currentTheme = _themeType;
      notifyListeners();
    } catch (e) {
      debugPrint('加载主题偏好设置失败: $e');
    }
  }

  /// 保存主题偏好设置
  Future<void> _saveThemePreference(ThemeType themeType) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setInt(_themePreferenceKey, themeType.index);
    } catch (e) {
      debugPrint('保存主题偏好设置失败: $e');
    }
  }

  /// 使用系统默认主题
  void _setSystemTheme() {
    final brightness =
        WidgetsBinding.instance.platformDispatcher.platformBrightness;
    _themeType =
        brightness == Brightness.dark ? ThemeType.dark : ThemeType.light;
    AppTheme.currentTheme = _themeType;
    notifyListeners();
  }

  /// 切换主题
  void toggleTheme() {
    _themeType =
        _themeType == ThemeType.light ? ThemeType.dark : ThemeType.light;
    AppTheme.currentTheme = _themeType;
    _saveThemePreference(_themeType);
    notifyListeners();
  }

  /// 设置为浅色主题
  void setLightTheme() {
    _themeType = ThemeType.light;
    AppTheme.currentTheme = _themeType;
    _saveThemePreference(_themeType);
    notifyListeners();
  }

  /// 设置为深色主题
  void setDarkTheme() {
    _themeType = ThemeType.dark;
    AppTheme.currentTheme = _themeType;
    _saveThemePreference(_themeType);
    notifyListeners();
  }

  /// 使用系统主题
  void useSystemTheme() {
    _setSystemTheme();
    _saveThemePreference(_themeType);
  }
}
